const axios = require('axios');
const config = require('../config');

/**
 * 清理输入文本，移除Markdown格式
 * @param {string} input - 原始输入文本
 * @returns {string} 清理后的文本
 */
function cleanMarkdownInput(input) {
    if (!input) return '';
    
    // 移除代码块标记
    let cleaned = input.replace(/```[\s\S]*?```/g, (match) => {
        // 移除```json, ```js等语言标记
        return match.replace(/```\w*\n/, '').replace(/```$/, '');
    });
    
    // 移除行内代码标记
    cleaned = cleaned.replace(/`([^`]+)`/g, '$1');
    
    // 移除标题标记
    cleaned = cleaned.replace(/^#+\s+/gm, '');
    
    // 移除列表标记
    cleaned = cleaned.replace(/^[-*+]\s+/gm, '');
    cleaned = cleaned.replace(/^\d+\.\s+/gm, '');
    
    // 移除表格标记
    cleaned = cleaned.replace(/\|[-:]+\|/g, '');
    cleaned = cleaned.replace(/\|/g, '');
    
    // 移除引用标记
    cleaned = cleaned.replace(/^>\s+/gm, '');
    
    // 移除多余的空行
    cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
    
    // 移除首尾空白
    cleaned = cleaned.trim();
    
    return cleaned;
}

/**
 * 从代码或文档生成HAR格式的HTTP请求
 * @param {string} input - 后端代码或API文档
 * @returns {Promise<object>} HAR格式的HTTP请求
 */
async function generateHarFromCode(input) {
    try {
        // 清理输入文本
        const cleanedInput = cleanMarkdownInput(input);
        
        const prompt = `请根据以下代码或文档生成一个HAR格式的HTTP请求示例。HAR格式应该包含完整的请求信息，包括headers、query parameters、request body等。
        
输入内容：
${cleanedInput}

请以JSON格式返回HAR格式的HTTP请求，格式如下：
{
    "log": {
        "entries": [
            {
                "request": {
                    "method": "HTTP方法",
                    "url": "完整URL",
                    "headers": [
                        {
                            "name": "header名称",
                            "value": "header值"
                        }
                    ],
                    "queryString": [
                        {
                            "name": "参数名",
                            "value": "参数值"
                        }
                    ],
                    "postData": {
                        "mimeType": "application/json",
                        "text": "请求体内容"
                    }
                }
            }
        ]
    }
}`;

        const response = await axios.post(config.qwen.apiUrl, {
            model: "qwen-max",
            input: {
                messages: [
                    {
                        role: "system",
                        content: "你是一个专业的API开发助手，擅长将代码和文档转换为标准的HAR格式HTTP请求。请直接返回JSON格式的响应，不要包含任何其他内容。"
                    },
                    {
                        role: "user",
                        content: prompt
                    }
                ]
            },
            parameters: {
                temperature: 0.3,
                result_format: "message"
            }
        }, {
            headers: {
                'Authorization': `Bearer ${config.qwen.apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        // 通义千问的响应格式与DeepSeek不同，需要提取content字段
        return response.data.output.choices[0].message.content;
    } catch (error) {
        console.error('生成HAR格式请求时出错:', error);
        throw new Error('生成HAR格式请求失败: ' + error.message);
    }
}

module.exports = {
    generateHarFromCode
}; 